//
//  DYSimilarPhotoVC.m
//  PrivatePhoto
//
//  Created by PrivatePhoto Team on 2021.
//  Copyright © 2021年 PrivatePhoto Team. All rights reserved.
//

#import "DYSimilarPhotoVC.h"
#import "DYSimilarPicCell.h"
#import "WKClearPhotoManager.h"
#import "DYSimilarPicCellModel.h"
#import "FPPhotosTool.h"
#import "DYVideoPlayerVC.h"


@interface DYSimilarPhotoVC () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, weak) UIButton *rightBtn;
@property (nonatomic, strong) DYSimilarPhotoVCModel *viewModel;
@property (nonatomic, assign) NSInteger totalCount;

@end

@implementation DYSimilarPhotoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configSubView];
    [self bindViewModel];
}

- (void)configSubView{
    
    self.tableView.frame = CGRectMake(0, self.navigationBarHeight, kScreenWidth, kScreenHeight-self.navigationBarHeight-kBottomSafeHeight);
    [self.view addSubview:self.tableView];
    
}

- (UIBarButtonItem *)rightBarButtonItem
{
    UIButton *button = [[UIButton alloc] init];
    [button setTitle:@"取消全选"forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithHexString:@"#528CFF"] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 80, 22);
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [button addTarget:self action:@selector(rightBarButtonItemDidClick:) forControlEvents:UIControlEventTouchUpInside];
    self.rightBtn = button;
    return [[UIBarButtonItem alloc] initWithCustomView:button];
}

- (void)bindViewModel{
    @weakify(self)
    [RACObserve(self, viewModel.seletedCount) subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        BOOL isSeletedAll = self.viewModel.seletedCount >= self.viewModel.originPicArray.count;
        NSString *title = !isSeletedAll ? @"选择全部":@"取消全选";
        [self.rightBtn setTitle:title forState:UIControlStateNormal];
        
    }];
    
    [RACObserve(self, totalCount) subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        [self setNavigationItemTitleViewWithTitle:[NSString stringWithFormat:@"选定%ld张照片",(long)self.totalCount]];
    }];
  
}

#pragma mark - UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;//viewModel.dataArr
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DYSimilarPicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DYSimilarPicCell"];
    DYSimilarPicCellModel *item = self.dataArray[indexPath.row];
    [cell bindWithModel:item];
    
    @weakify(self)
    cell.lookDetailBlock = ^(DYSimilarPicModel *info, NSInteger index, NSArray *array) {
        @strongify(self)
        if (info.is_video) {
            DYVideoPlayerVC *vc = [[DYVideoPlayerVC alloc] init];
            vc.asset = info.asset;
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:vc animated:YES completion:nil];
        }else{
            [FPPhotosTool browserImagesWithAssetArray:array index:index];
        }
    };
    
    cell.selectPhotoCompleteBlock = ^(DYSimilarPicModel *info, BOOL isAdd, NSMutableArray *array) {
        @strongify(self)
        self.viewModel.currentIsAdd = isAdd;
        if ([self.viewModel.seletedPicArray containsObject:info]) {
            if (isAdd) {return;}
            [self.viewModel.seletedPicArray removeObject:info];
        }else{
            if (!isAdd) {return;}
            [self.viewModel.seletedPicArray addObject:info];
        }
     
        if ([array containsObject:item.bigItem]) {
            if (isAdd) {
                self.totalCount ++;
            }else{
                self.totalCount --;
            }
            self.viewModel.seletedCount = self.viewModel.seletedPicArray.count-1;
            
        }else{
            self.viewModel.seletedCount = self.viewModel.seletedPicArray.count;
            self.totalCount = self.viewModel.seletedCount;
        }
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.dataArray.count) {return 0.01;}//viewModel.dataArr
    DYSimilarPicCellModel *item = self.dataArray[indexPath.row];
    return item.viewHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)leftBarButtonItemDidClick{
    !self.seletedPhotoCompleteBlock ?:self.seletedPhotoCompleteBlock(self.viewModel, self.vcType);
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightBarButtonItemDidClick:(UIButton *)sender{

    if (sender.selected) {
        sender.selected = NO;
        [self handleCellSelectedViewShow];
    }else{
        sender.selected = YES;
        [self handleCellCancelSeletedViewShow];
    }
}

- (void)handleCellSelectedViewShow{
    [self.viewModel.seletedPicArray removeAllObjects];
    [self.viewModel.seletedPicArray addObjectsFromArray:self.viewModel.originPicArray];
    self.viewModel.seletedCount = self.viewModel.seletedPicArray.count;
    @weakify(self)
    [self.dataArray enumerateObjectsUsingBlock:^(DYSimilarPicCellModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj.seletedArray removeAllObjects];
        [obj.bigViewSeletedArray removeAllObjects];
        [obj.mutiViewSeletedArray removeAllObjects];
        
        [obj.seletedArray addObjectsFromArray:obj.allImgArray];
        obj.seletedCount = obj.seletedArray.count;
        [obj.bigViewSeletedArray addObjectsFromArray:obj.bigViewOthersArray];
        [obj.mutiViewSeletedArray addObjectsFromArray:obj.mutiViewSeletedArray];
        @strongify(self)
        [self.tableView reloadData];
        
    }];
   
}

- (void)handleCellCancelSeletedViewShow{
    [self.viewModel.seletedPicArray removeAllObjects];
    self.viewModel.seletedCount = 0;
    @weakify(self)
    [self.dataArray enumerateObjectsUsingBlock:^(DYSimilarPicCellModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj.seletedArray removeAllObjects];
        [obj.bigViewSeletedArray removeAllObjects];
        [obj.mutiViewSeletedArray removeAllObjects];
        obj.seletedCount = obj.seletedArray.count;
        @strongify(self)
        [self.tableView reloadData];
    }];
//    [self.tableView reloadData];
}

- (void)handleViewModelData{
//    [self.viewModel.dataArr removeAllObjects];
//    [self.viewModel.dataArr addObjectsFromArray:self.dataArray];
    [self.viewModel.originPicArray removeAllObjects];
    [self.viewModel.seletedPicArray removeAllObjects];
    for (DYSimilarPicCellModel *model in self.dataArray) {
        for (int i = 0; i < model.seletedArray.count; i++) {
            DYSimilarPicModel *item = model.seletedArray[i];
            [self.viewModel.seletedPicArray addObject:item];
            [self.viewModel.originPicArray addObject:item];
        }
    }
    self.viewModel.seletedCount = self.viewModel.seletedPicArray.count;
    self.totalCount = self.viewModel.originPicArray.count;
    [self setNavigationItemTitleViewWithTitle:[NSString stringWithFormat:@"选定%ld张照片",(long)self.totalCount]];
}


#pragma mark - 懒加载

- (void)setDataArray:(NSArray *)dataArray{
    _dataArray = dataArray;

    [self handleViewModelData];
    [self.tableView reloadData];

}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 60;
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _tableView.delaysContentTouches = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
     if ([UIDevice currentDevice].systemVersion.floatValue >= 11.0) {
            _tableView.estimatedRowHeight = 0;
            if ([UIScreen mainScreen].bounds.size.height == 812) {
                if (@available(iOS 11.0, *)) {
                    _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
                } else {
                    // Fallback on earlier versions
                }
            }
        } else {}
        
        [_tableView registerClass:[DYSimilarPicCell class] forCellReuseIdentifier:@"DYSimilarPicCell"];
        
    }
    
    return _tableView;
}

- (DYSimilarPhotoVCModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[DYSimilarPhotoVCModel alloc] init];
    }
    return _viewModel;
}

@end

